package com.example.blackmarket.module.Me.Recharge;

import android.os.Handler;
import android.util.Log;

import com.example.blackmarket.entities.FailureResponse;
import com.example.blackmarket.entities.TradeInfo;
import com.example.blackmarket.model.BlackMarketApi;
import com.example.blackmarket.module.Base.BasePresenter;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AliPayPresenter extends BasePresenter<AlipayView> {
    private Handler mHandler;

    public AliPayPresenter(AlipayView alipayView) {
        this.attachView(alipayView);
        mHandler = new Handler();
    }

    public void recharge(float money) {
        BlackMarketApi.recharge(money, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                onFail(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    assert response.body() != null;
                    String data = response.body().string();
                    mHandler.post(() -> onSuccess(data));
                }
                else {
                    assert response.body() != null;
                    String msg = response.body().string();
                    Log.e("response failure",msg);
                    mHandler.post(()->onFail(msg));
                }
            }
        });
    }

    public void onSuccess(Object data) {
        Log.e("return token",data.toString());
        TradeInfo tradeInfo = new Gson().fromJson((String) data, TradeInfo.class);
        String response = tradeInfo.getResponse();
        if(isViewAttached())
            this.getView().showSuccess(response);
    }


    public void onFail(String msg) {
        FailureResponse failureResponse = new Gson().fromJson(msg, FailureResponse.class);
        if(isViewAttached())
            this.getView().showFailure(failureResponse);
    }
}
